package com.xinqi.common.third.oss.slice.event;

import com.aliyun.imm20200930.Client;
import com.aliyun.imm20200930.models.CreateOfficeConversionTaskRequest;
import com.aliyun.imm20200930.models.CreateOfficeConversionTaskResponse;
import com.aliyun.imm20200930.models.Notification;
import com.aliyun.imm20200930.models.RocketMQ;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.ListObjectsRequest;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.Common;
import com.aliyun.teautil.models.RuntimeOptions;
import com.xinqi.common.base.utils.json.JSON;
import com.xinqi.common.core.constant.Constants;
import com.xinqi.common.third.oss.slice.config.OssSliceConfig;
import com.xinqi.common.third.oss.slice.dto.UserDataDTO;
import com.xinqi.common.third.util.FileUtils;
import com.xinqi.common.third.util.UuidUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 阿里云切片
 *
 * @author dzy
 */
@Log4j2
@Service
@RequiredArgsConstructor
public class OssSliceEvent {

    private final OssSliceConfig ossSliceConfig;

    /**
     * 获取客户端凭证
     *
     * @author dzy
     */
    public Client createClient() throws Exception {
        Config config = new Config()
            // 必填，您的 AccessKey ID
            .setAccessKeyId(ossSliceConfig.getAccessKey())
            // 必填，您的 AccessKey Secret
            .setAccessKeySecret(ossSliceConfig.getScreenKey());
        config.endpoint = ossSliceConfig.getEndPoint();
        return new Client(config);
    }

    /**
     * 阿里生成切片方法
     *
     * @author dzy
     */
    public void createSliceImage(String url, Long key, String type) {
        try {
            url = url.replace(ossSliceConfig.getOssSourceHttpsUrl(), "");
            url = url.replace(ossSliceConfig.getOssSourceHttpUrl(), "");
            // 生成日期地址
            String targetUrl = ossSliceConfig.getTargetUrlPrefix() + LocalDate.now() + "/" + key + "/" + UuidUtils.getUUID32() + "/";
            // 唯一值设置
            UserDataDTO userDataDTO = new UserDataDTO();
            userDataDTO.setKey(key);
            userDataDTO.setType(type);
            userDataDTO.setFolder(targetUrl);
            userDataDTO.setSuffix(FileUtils.getSuffix(url).toLowerCase());
            // 切片请求凭证
            Client client = createClient();
            RocketMQ notificationMQ = new RocketMQ().setTopicName(ossSliceConfig.getMqTopic())
                .setInstanceId(ossSliceConfig.getMqInstanceId());
            CreateOfficeConversionTaskRequest createOfficeConversionTaskRequest = new CreateOfficeConversionTaskRequest()
                .setProjectName(ossSliceConfig.getProjectName()).setSourceURI(ossSliceConfig.getSourceUrlPrefix() + url)
                .setTargetURIPrefix(targetUrl).setTargetType(ossSliceConfig.getTargetType())
                .setUserData(JSON.stringify(userDataDTO)).setNotification(new Notification().setRocketMQ(notificationMQ));
            RuntimeOptions runtime = new RuntimeOptions().setAutoretry(true).setMaxAttempts(5);
            CreateOfficeConversionTaskResponse resp
                = client.createOfficeConversionTaskWithOptions(createOfficeConversionTaskRequest, runtime);
            log.info(Common.toJSONString(resp));
        } catch (TeaException error) {
            // 如有需要，请打印 error
            log.info(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            log.info(error.message);
        }
    }

    /**
     * 阿里获取切片方法
     *
     * @author dzy
     */
    public List<String> getSliceImage(String folder, String type) {
        List<String> fileList = new ArrayList<>();
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = ossSliceConfig.getOssEndpoint();
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        DefaultCredentialProvider credentialsProvider =
            CredentialsProviderFactory.newDefaultCredentialProvider(ossSliceConfig.getAccessKey(), ossSliceConfig.getScreenKey());
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
        try {
            // 构造ListObjectsRequest请求。
            ListObjectsRequest listObjectsRequest = new ListObjectsRequest(ossSliceConfig.getOssBucketName());
            // 设置prefix参数来获取目录下的所有文件。
            folder = folder.replace(ossSliceConfig.getTargetUrlPrefix(), "");
            listObjectsRequest.setPrefix(folder);
            listObjectsRequest.setMaxKeys(1000);

            // 递归列举目录下的所有文件。
            ObjectListing listing = ossClient.listObjects(listObjectsRequest);

            // 遍历所有文件。
            folder = folder.replace(ossSliceConfig.getTargetUrlPrefix(), "");
            if (Objects.equals(Constants.XLS_SUF, type) || Objects.equals(Constants.XLSX_SUF, type) || Objects.equals(Constants.CSV_SUF, type)) {
                for (OSSObjectSummary summary : listing.getObjectSummaries()) {
                    fileList.add(ossSliceConfig.getOssHttpsUrl() + FileUtils.getFileName(summary.getKey()));
                }
                ;
            } else {
                for (int i = 1; i <= listing.getObjectSummaries().size(); i++) {
                    fileList.add(ossSliceConfig.getOssHttpsUrl() + folder + i + ".png");
                }
            }
        } catch (OSSException oe) {
            log.info("获取OSS文件集合失败:{}", oe.getErrorMessage());
        } catch (ClientException ce) {
            log.info("获取OSS文件集合失败:{}", ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return fileList;
    }

    public static void main(String[] args) {
        String str = URLEncoder.encode("/2023-09-03/488769012134613125/f75faf388b394aa7bc40f357ca664a93/%E4%B8%AA%E4%BA%BA%E4%B8%AD%E5%BF%83_1_01.png");
        System.out.println(str);
    }

}
